<template>
    <div class="result" v-loading="loadState.isLoading" :element-loading-text="loadState.loadingText"
        :element-loading-spinner="loadState.svg" element-loading-svg-view-box="-10, -10, 50, 50">
        <el-result icon="success" :title="resultTitle" :sub-title="`自动返回剩余${timeLeft}秒`" v-show="!loadState.isLoading">
            <template #extra>
                <el-button type="primary" link @click="handleRedirect">立即返回</el-button>
            </template>
        </el-result>
    </div>
</template>

<script setup>
import { bindUser } from "@/api/system/userprofile"
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const route = useRoute();
const router = useRouter();
const timeLeft = ref(3);
const resultTitle = ref();
const redirectUrl = ref('/');


const loadState = reactive({
    isLoading: false,
    loadingText: "正在验证...",
    svg: `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `
})


const removeQueryParam = (fullPath, paramName) => {
    const url = new URL(fullPath, window.location.origin); // 确保构造一个完整 URL
    url.searchParams.delete(paramName); // 删除指定参数
    return url.pathname + url.search; // 返回修改后的路径和查询参数
}

const startCountdown = (callback) => {
    loadState.isLoading = false;
    const timer = setInterval(() => {
        if (timeLeft.value > 1) {
            timeLeft.value--;
        } else {
            loadState.isLoading = true;
            loadState.loadingText = "正在进行跳转..."
            clearInterval(timer);
            if (typeof callback === "function") {
                callback(); // 倒计时结束后执行回调
            }
        }
    }, 1000);
};


const handleBindUser = (data) => {
    resultTitle.value = "绑定成功";
    bindUser(data).then(res => {
        startCountdown(handleRedirect);
    })
}

const handleLogin = (data) => {
    resultTitle.value = "登录成功";

    userStore.socialLogin(data.code, data.provider, data.redirectUrl).then(res => {
        startCountdown(handleRedirect);
    }).catch((error) => {
        console.error('OAuth授权失败:', error);
        redirectUrl.value = '/login';
        handleRedirect();
    });
}

const handleRedirect = () => {
    router.push(redirectUrl.value);
}


onMounted(() => {
    // 获取 URL 参数中的授权码和状态
    loadState.isLoading = true;

    const { code, provider, op, redirect_url } = route.query;
    redirectUrl.value = redirect_url || '/';
    let callbackPath = removeQueryParam(route.fullPath, "code");
    let data = { code, provider, redirectUrl: callbackPath }
    switch (op) {
        case "login":
            handleLogin(data);
            break;
        case "bind":
            handleBindUser(data);
            break;
        default:
            break;
    }
});
</script>

<style scoped>
/* 页面样式 */
h1 {
    text-align: center;
    margin-top: 50px;
}

.result {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>